# -*- coding: utf-8 -*

# 验证码识别，此程序只能识别数据验证码

from PIL import Image

from pytesseract import *
import os

from Config import tesseract_path

pytesseract.tesseract_cmd = 'D:\\pythonVcl\\Tesseract-OCR\\tesseract.exe'
tessdata_dir_config = '--tessdata-dir "D:\\pythonVcl\\Tesseract-OCR\\tessdata"'

class VerificationCode(object):
	# 二值化
	threshold = 140
	table = []
	for i in range(256):
		if i < threshold:
			table.append(0)
		else:
			table.append(1)

	#由于都是数字
	#对于识别成字母的 采用该表进行修正
	rep={'O':'0',
		'I':'1',
		'L':'1',
		'Z':'2',
		'S':'8'
		};

	def getVerificationCode(self,fileName):
			# 二值化
			#print ("os.path.dirname(os.path.realpath(__file__))=%s" % os.path.dirname(os.path.realpath(__file__)))
			#pytesseract.tesseract_cmd = 'C:/Program Files (x86)/Tesseract-OCR/tesseract.exe'

			#pytesseract.tesseract_cmd = '%s\\Tesseract-OCR\\tesseract.exe' % os.path.dirname(os.path.realpath(__file__))
			pytesseract.tesseract_cmd = tesseract_path
			#print (pytesseract.tesseract_cmd)
			img=Image.open(fileName)
			width = img.size[0]  # 长度
			height = img.size[1]  # 宽度
			for i in range(0, width):  # 遍历所有长度的点
				for j in range(0, height):  # 遍历所有宽度的点
					try:
						data = (img.getpixel((i, j)))  # 打印该图片的所有点
						if (data[0] != 255 and data[1] != 255 and data[2] !=255):
							img.putpixel((i, j), (0, 0, 0,0))
					except Exception as e:
						continue

			#转化到灰度图
			imgry = img.convert('L')
			#保存图像
			imgry.save('./code2.png')
			#二值化，采用阈值分割法，threshold为分割点
			img = imgry.point(self.table,'1')
			text = pytesseract.image_to_string(img,config=tessdata_dir_config)
			#print ("识别验证码结果 = ",text)
			return text


	def getCode(self,path =r'./code.png'):
		# 二值化
		#pytesseract.tesseract_cmd = 'D:\\pythonVcl\\Tesseract-OCR\\tesseract.exe' % os.path.dirname(os.path.realpath(__file__))

		print (pytesseract.tesseract_cmd)
		img = Image.open(path)
		code = pytesseract.image_to_string(img,config=tessdata_dir_config)
		print (code)
		return code
#getYjdCode()
